package com.campus.food.exception;

import com.campus.food.model.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-06-02
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        e.printStackTrace();
        log.error("业务异常: {}", e.getMessage());
        return Result.failure(e.getCode(), e.getMessage(), request.getRequestURI());
    }
    
    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<?> handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        e.printStackTrace();
        log.error("权限不足: {}", e.getMessage());
        return Result.failure(HttpStatus.FORBIDDEN.value(), "权限不足，禁止访问", request.getRequestURI());
    }
    
    /**
     * 处理认证异常
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result<?> handleAuthenticationException(AuthenticationException e, HttpServletRequest request) {
        log.error("认证异常: {}", e.getMessage());
        e.printStackTrace();
        String message = "认证失败";
        if (e instanceof BadCredentialsException) {
            message = "用户名或密码错误";
        }
        return Result.failure(HttpStatus.UNAUTHORIZED.value(), message, request.getRequestURI());
    }
    
    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationException(MethodArgumentNotValidException e, HttpServletRequest request) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, String> errors = fieldErrors.stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (a, b) -> a));
        e.printStackTrace();
        log.error("参数校验失败: {}", errors);
        
        // 构建详细的错误消息
        StringBuilder detailMessage = new StringBuilder();
        errors.forEach((field, message) -> 
            detailMessage.append(field).append(": ").append(message).append("; ")
        );
        
        // 如果需要同时保留errors数据，可以选择以下两种方式：
        // 方式1：同时在message和data中包含错误信息
        return Result.failure(HttpStatus.BAD_REQUEST.value(), detailMessage.toString(), errors, request.getRequestURI());
        
        // 方式2：只在message中包含错误信息，data字段为null
        // return Result.failure(HttpStatus.BAD_REQUEST.value(), detailMessage.toString(), request.getRequestURI());
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<?> handleBindException(BindException e, HttpServletRequest request) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map<String, String> errors = fieldErrors.stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (a, b) -> a));
        e.printStackTrace();
        log.error("参数绑定失败: {}", errors);
        
        // 构建详细的错误消息
        StringBuilder detailMessage = new StringBuilder();
        errors.forEach((field, message) -> 
            detailMessage.append(field).append(": ").append(message).append("; ")
        );
        
        return Result.failure(HttpStatus.BAD_REQUEST.value(), detailMessage.toString(), errors, request.getRequestURI());
    }
    
    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        log.error("参数类型不匹配: {}", e.getMessage());
        e.printStackTrace();
        return Result.failure(HttpStatus.BAD_REQUEST.value(), 
                String.format("参数类型不匹配，参数[%s]应为[%s]类型", e.getName(), e.getRequiredType().getSimpleName()), 
                request.getRequestURI());
    }
    
    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: ", e);
        e.printStackTrace();
        return  Result.failure( 500,"系统异常：" + e.getMessage(), request.getRequestURI());
    }

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(RequestRejectedException.class)
    public Result<?> requestRejectedExceptio(Exception e, HttpServletRequest request) {
        log.error("系统异常: ", e);
        e.printStackTrace();
        return  Result.failure( 404,"唔该资源" + e.getMessage(), request.getRequestURI());
    }
} 